/*
 * $Id: isbn.c,v 1.2 2005-12-15 16:08:56 bacon Exp $
 */

#include <xp/utl/isbn.h>
#include <xp/bas/string.h>

/*
 * An ISBN has 10 digits, separated by hyphens. The ISBN is divided into 4 parts: 
 *   Group identifier (1 digit, typically 0 or 1 for English-speaking countries) 
 *   Publisher identifier 
 *   Title identifier 
 *   Check digit 
 * 
 * The check digit is used to validate the preceding 9 digits. 
 * The check digit will sometimes be an X. 
 * All other characters must be numeric. 
 */

xp_bool_t xp_is_isbn_valid (const xp_char_t* isbn)
{
	return xp_is_isbnx_valid (isbn, xp_strlen(isbn));
}
  
xp_bool_t xp_is_isbnx_valid (const xp_char_t* isbn, xp_size_t len)
{
	unsigned int checksum = 0;	
	xp_size_t i, x;

	if (len != 10) return xp_false;

	for (i = 0; i < 9; i++) {
		checksum += (i + 1) * (isbn[i] - XP_CHAR('0'));
	}

	x = (isbn[9] == XP_CHAR('X'))? 10: (isbn[9] - XP_CHAR('0'));
	return (checksum % 11) == x;
}
